package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import com.fasterxml.jackson.databind.util.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Api(tags = "01.用户管理模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    //@RequestBody,将json数据转换为对象
    //@ResponseBody,将对象转换为json数据

    @PostMapping("reg")
    @ApiOperation("用户注册")

    public JsonResult userReg(@RequestBody @Validated UserRegDTO userRegDTO) {
        log.debug("userRegDTO = " + userRegDTO);

        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO != null) {
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @PostMapping("login")
    @ApiOperation("用户登录")
    public JsonResult userLogin(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("userLoginDTO = " + userLoginDTO);

        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginDTO.getPassword())) {
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
        session.setAttribute("user", userVO);
        return JsonResult.ok();
    }

    @GetMapping("currentUser")
    @ApiOperation("获取当前登录用户信息")
    @ApiImplicitParam(name = "session", value = "用户会话对象", required = true, dataType = "HttpSession")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    @GetMapping("logout")
    @ApiOperation("用户退出")
    @ApiImplicitParam(name = "session", value = "用户会话对象", required = true, dataType = "HttpSession")
    public JsonResult userLogout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
